<?php

namespace App\Http\Controllers\Index;

use App\Http\Controllers\WxController;
use App\Models\User;
use App\Utils\CodeUtil;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class IndexController extends Controller
{
    /**
     * 前后端完全分离微信登陆
     * 使用扩展  overtrue/laravel-wechat
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function wxLogin(Request $request) {
        $encryptedData = urldecode(request('encryptedData', ''));
        $iv = urldecode(request('iv', ''));
        $config = [
            'app_id' => config("wechat.mini_program.default.app_id"),
            'secret' => config("wechat.mini_program.default.secret"),
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = EasyWeChat\Factory::miniProgram($config);
        $result = $app->auth->session($request->input("code"));
        $decryptedData = $app->encryptor->decryptData($result["session_key"], $iv, $encryptedData);
        $user = User::where("openid",$decryptedData["openId"])->first();
        if(empty($user)) {
            $user = new User();
            $user->name = $decryptedData["openId"];
            $user->email = $decryptedData["openId"];
            $user->password = $decryptedData["openId"];
            $user->realname = $decryptedData["nickName"];
            $user->thumb  = $decryptedData["avatarUrl"];
            $user->openid = $decryptedData["openId"];
            $user->create();
        }
        $token  = $user->createToken('xcx')->accessToken;
        return response()->json(['code'=>200,'msg'=>'登陆成功',"data"=>["access_token"=>$token]]);
    }
}
